package com.shungen.realapigateway.service.impl;

import com.shungen.realapigateway.service.NonceService;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class NonceInMemoryService implements NonceService {

    private final Map<String, Long> nonceStore = new ConcurrentHashMap<>();

    // 设置nonce的有效期（例如5分钟）
    private static final long NONCE_EXPIRATION_TIME = 5 * 60 * 1000;

    @Override
    public boolean isNonceUsed(String nonce) {
        Long timestamp = nonceStore.get(nonce);
        if (timestamp == null) {
            return false;
        }

        // 检查 nonce 是否过期
        long currentTime = System.currentTimeMillis();
        if (currentTime - timestamp > NONCE_EXPIRATION_TIME) {
            nonceStore.remove(nonce);
            return false;
        }

        return true;
    }

    @Override
    public void saveNonce(String nonce) {
        long currentTime = System.currentTimeMillis();
        nonceStore.put(nonce, currentTime);

        // 定期清理过期的 nonce
        nonceStore.entrySet().removeIf(entry -> currentTime - entry.getValue() > NONCE_EXPIRATION_TIME);
    }
}
